<template>
  <div class="login-container">
    <h2 style="margin-top: 60px;text-align: center;color: #FFF;text-shadow: 5px 5px 20px lightyellow"><i
      class="el-icon-coffee-cup"></i>分布式个人理财管理系统</h2>
    <div class="loginForm">
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane label="用户登录" name="userlogin">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="loginUser.identify" placeholder="请输入注册手机/邮箱/账号"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="loginUser.password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <img :src="randomCodeImgUrl" style="width: 120px;cursor:pointer" title="看不清楚，点击换一张"
                   @click="changeRandomCodeImgUrl"/>
            </el-form-item>
            <el-form-item label="验证码">
              <el-input v-model="loginUser.code" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item label="" style="margin-bottom: 0px">
              记住我
              <el-switch
                v-model="rememberme"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              <div style="display: inline;vertical-align: middle">&nbsp;&nbsp;第三方登录 <a href="#"><img
                src="@/assets/images/QQ_logo.png" style="width:22px;vertical-align: middle;cursor: pointer;"></a> <img
                src="@/assets/images/weixni_logo.png" style="width:22px;vertical-align: middle;cursor: pointer;">
              </div>
            </el-form-item>

            <el-form-item label="">
              <el-button style="width: 80%; display: block" @click="handleLogin" type="primary" plain>登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="用户注册" name="userreg">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="regUser.identify" placeholder="请输入注册手机/邮箱"></el-input>
            </el-form-item>
            <el-form-item label="">

              <el-button :disabled="sendMsgDisabled" @click="sendMessage">{{
                  sendMsgBtnTitle
                }}
              </el-button>
              <!--
              <img src="../../assets/images/vcode.png" title="看不清楚，换一张" style="cursor:pointer" @click="changeRandomCodeImg">
              -->
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="regUser.password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input v-model="regUser.confirmpass" placeholder="请输入确认密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="验证码">
              <el-input v-model="regUser.validateCode" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-button style="width: 80%; display: block" type="success" @click="doReg" plain>注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-divider>阿里云</el-divider>
    <div style="text-align: center">
      <el-link type="primary" disabled>华清远见西安中心 &copy;2020-2024 &nbsp;作者：西蒙牛</el-link>
    </div>
  </div>
</template>

<script>
//import { validUsername } from '@/utils/validate'

import outils from "outils";
import {nanoid} from "nanoid";
import lodash from "lodash";
//引入加密和解密工具库
import {decrypt, encrypt} from '@/utils/crypto'

export default {
  name: 'Login',
  data() {
    return {
      sendMsgDisabled: false,
      sendMsgBtnTitle: '发送验证码',
      isPassing: false,
      value: "",
      randomCodeImgUrl: '',
      imgsrcList: ["https://img.simoniu.com/huakuai01.jpg", "https://img.simoniu.com/huakuai02.jpg", "https://img.simoniu.com/huakuai03.jpg", "https://img.simoniu.com/huakuai04.jpg", "https://img.simoniu.com/huakuai05.jpg"],
      imgsrc: '',
      activeName: "userlogin",
      token: nanoid(16), //客户产生的令牌
      rememberme: true,
      loginUser: {
        identify: '',
        password: '',
        token: '',
        code: ''
      },
      loginSuccessUser: {}, //登录成功的用户对象
      regUser: {
        identify: "", //输入的电子邮箱或者手机号码
        email: "",
        mobile: "",
        password: "",
        confirmpass: "",
        validateCode: "",
        flag: 1
      }
    }
  },

  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    console.log("---------客户端生成的令牌是---------")
    console.log(this.token);
    this.randomCodeImgUrl = '/api/user/code/randomCodeImg?token=' + this.token + "&tm=" + new Date().getTime()
    if (outils.getCookie("finance.site.com.identify")) {
      this.loginUser.identify = decrypt(outils.getCookie("finance.site.com.identify"));
      this.loginUser.password = decrypt(outils.getCookie("finance.site.com.password"));
    }
  },
  methods: {

    changeRandomCodeImgUrl() {
      this.randomCodeImgUrl = '/api/user/code/randomCodeImg?token=' + this.token + "&tm=" + new Date().getTime()
    },
    async regFormValidate() {
      //检查手机或者邮箱格式是否合法
      if (outils.isPhoneNum(this.regUser.identify)) {
        this.regUser.mobile = this.regUser.identify;
        return true;
      } else if (outils.isEmail(this.regUser.identify)) {
        this.regUser.email = this.regUser.identify;
        return true;
      } else {
        this.$message({
          type: 'error',
          message: '注册信息格式非法！'
        })
        return false;
      }
    },

    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    async sendMessage() {
      if (!await this.regFormValidate()) {
        return;
      }

      await this.$store.dispatch('user/checkIdentifyCanReg', this.regUser.identify).then(resp => {
        console.log(resp);
        if (resp.code === 200) {
          console.log('该手机或者邮箱可以注册....')
          let params = {
            token: this.token,
            identify: this.regUser.identify
          }
          //真正发送验证码
          this.$store.dispatch('common/sendMessageWithMobileOrEmail', params).then(resp => {
            if (resp.code === 200) {
              //短信验证码发送成功弹出消息框
              this.$message({
                type: 'success',
                message: resp.msg
              })

              //把发送按钮置为不可以用
              this.sendMsgDisabled = true;
              let counter = 60;
              let html = "";
              let countDownTimer = setInterval(() => {
                html = "发送验证码(" + counter + ")";
                this.sendMsgBtnTitle = html;
                counter--;

                if (counter < 0) {
                  clearInterval(countDownTimer);
                  this.sendMsgDisabled = false;
                  this.sendMsgBtnTitle = "发送验证码";
                }
              }, 1000);
            }
          })
        } else {
          console.log('该手机或者邮箱已经被注册....')
        }
      })

    },

    handleLogin() {
      console.log("-----执行用户登录!------")
      console.log(this.loginUser);
      this.loginUser.token = this.token;

      this.$store.dispatch('user/login', this.loginUser).then((resp) => {
        console.log("------调用后端登录接口后返回的数据--------")
        console.log(resp);
        if (resp.code === 200) {
          this.$message({
            type: 'success',
            message: resp.msg
          })

          //使用要记住我
          if (this.rememberme) {
            outils.setCookie("finance.site.com.identify", encrypt(this.loginUser.identify), 100);
            outils.setCookie("finance.site.com.password", encrypt(this.loginUser.password), 100);
          } else {
            outils.removeCookie("finance.site.com.identify");
            outils.removeCookie("finance.site.com.identify");
          }


          setTimeout(() => {
            this.$router.push({path: this.redirect || '/'})
          }, 1000)
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },

    doReg: lodash.debounce(async function () {
      console.log('执行用户注册');

      if (!await this.regFormValidate()) {
        return;
      }
      //下来检查密码的强度和密码与确认密码是否一致。
      if (this.regUser.password.length < 6) {
        this.$message({
          type: 'error',
          message: '密码不能少于6位。'
        })
        return;
      }

      if (this.regUser.password !== this.regUser.confirmpass) {
        this.$message({
          type: 'error',
          message: '密码与确认密码不一致！'
        })
        return;
      }

      let params = {
        token: this.token,
        code: this.regUser.validateCode
      };

      this.$store.dispatch('common/checkMessageIsRight', params).then(resp => {
        if (resp.code === 200) {
          //这里调用前端的用户注册接口
          this.$store.dispatch('user/reg', this.regUser).then(resp => {
            console.log(resp);
            if (resp.code === 200) {
              this.$message({
                type: 'success',
                message: resp.msg
              })
              //把注册用户的属性清空一下
              this.regUser.identify = "";
              this.regUser.password = "";
              this.regUser.mobile = '';
              this.regUser.confirmpass = "";
              this.regUser.validateCode = ""

              //跳转到登录
              setTimeout(() => {
                this.activeName = "userlogin";
              }, 1000)
            }
          })
        }
      })

    }, 2000)
  }
}
</script>


<style scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #2d3a4b;
  background-image: url("~@/assets/images/login-bg-2.jpg");
  background-size: cover;
  overflow: hidden;
}

.loginForm {
  margin: 60px auto;
  background: #bfcbd9;
  width: 480px;
  height: 430px;
  border-radius: 12px;
  box-shadow: 0px 0px 20px 2px lightsteelblue;
  opacity: 0.8;
}

.loginForm /deep/ .el-tabs__item {
  color: #FFF !important;
  font-size: larger;
  font-weight: bolder;
}

.loginForm /deep/ .el-tabs__item.is-active {
  color: steelblue !important;
}

.el-form-item {
  text-align: start;
}

.el-input {
  width: 280px;
}


</style>
